'use strict';
const uuid = require('uuid/v1');
const sendToWormhole = require('stream-wormhole');
const OSS = require('ali-oss');

const client = new OSS({
    region: 'oss-cn-beijing',
    accessKeyId: 'LTAIOgPgdlGUTFHl',
    accessKeySecret: 'F9zmK6ieRB6uLlnW5vAsf7XD9oJJYg',
    bucket: 'lvyueyang-blog'
});

const fileUploadOss = async (stream, filename) => {
    // 截取文件类型
    let fn = stream.filename;
    let t = fn.split('.');
    let len = t.length;
    let type = t[len - 1];
    // 拼接文件名
    let name = filename + '.' + type;
    let result;
    try {
        result = await client.putStream(name, stream);
    } catch (err) {
        // 必须将上传的文件流消费掉，要不然浏览器响应会卡死
        await sendToWormhole(stream);
        throw err;
    }
    return result
}
/*
* @ctx          context对象          必传
* @size         限制文件大小          默认2  单位M
* @ossname      上传到oss的路径       默认user
* @ossfilename  上传到oss的文件名称   默认用户ID
*/
const fileUploadImg = async (ctx, size = 2, ossname = 'user', ossfilename) => {
    const stream = await ctx.getFileStream();
    const ft = ['image/gif', 'image/jpeg', 'image/jpg', 'image/png', 'image/svg'];
    if (!ft.includes(stream.mimeType)) {
        ctx.throw(403, '请上传图片类型');
    }

    const filesize = parseInt((stream.readableLength / 1024) / 1024);
    if (filesize > size) {
        ctx.throw(403, '文件大大了，最多' + size + 'M');
    }
    let n = ossfilename || ctx.state.user._id;
    const filename = ossname + '/' + n;
    console.log(n)
    console.log(filename)
    // 文件处理，上传到阿里oss
    let result;
    try {
        result = await fileUpload(stream, filename);
    } catch (err) {
        ctx.throw(403, '文件上传失败');
    }
    const img = result.url;
    console.log(img)
    return img;
}

const Controller = require('../base.js');

class FileOssController extends Controller {
    // 上传头像图片
    async head() {
        const { ctx, app } = this;
        let headImg = await fileUploadImg(ctx);
        headImg += '?x-oss-process=style/head';
        const user = await ctx.service.user.update(ctx.state.user._id, { headImg });
        console.log(user)
        ctx.success({
            url: headImg,
            origin: 'oss'
        })
    }
    // 上传文章图片
    async article() {
        const { ctx, app } = this;
        const img = await fileUploadImg(ctx, 10, 'article', uuid());
        ctx.success({
            url: img,
            origin: 'oss'
        })

    }
}

module.exports = FileOssController;
